//
//  FaceBoard.m
//
//  Created by blue on 12-9-26.
//  Copyright (c) 2012年 blue. All rights reserved.
//  Email - 360511404@qq.com
//  http://github.com/bluemood

#import "FaceBoard.h"
#import "MessageView.h"


#define FACE_COUNT_ALL  128

#define FACE_COUNT_ROW  4

#define FACE_COUNT_CLU  7

#define FACE_COUNT_PAGE ( FACE_COUNT_ROW * FACE_COUNT_CLU )

#define FACE_ICON_SIZE  44

@interface FaceBoard ()
{
    int faceRowCount;               //每行表情个数
    int facePageCount;
    int faceRows;                   //行数
}
@end

@implementation FaceBoard

@synthesize delegate;

@synthesize inputTextField = _inputTextField;
@synthesize inputTextView = _inputTextView;

- (id)init {
    screenWidth = [UIScreen mainScreen].bounds.size.width;
    self = [super initWithFrame:CGRectMake(0, 0, screenWidth, 216)];
    if (self) {

        if (screenWidth>=414) {
            //IPHONE 6plus
            faceRowCount = 9;
        }
        else if (screenWidth>320) {
            //IPHONE 6
            faceRowCount = 8;
        }
        else {
            faceRowCount = 7;
        }
        
        faceRows = FACE_COUNT_ROW;
        facePageCount = faceRowCount*faceRows;
        
        self.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:236.0/255.0 blue:236.0/255.0 alpha:1];

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
        if ([[languages objectAtIndex:0] hasPrefix:@"zh"]) {

            _faceMap = [NSDictionary dictionaryWithContentsOfFile:
                         [[NSBundle mainBundle] pathForResource:@"expression_wds"
                                                         ofType:@"plist"]];
        }
        else {

            _faceMap = [NSDictionary dictionaryWithContentsOfFile:
                         [[NSBundle mainBundle] pathForResource:@"expression_wds"
                                                         ofType:@"plist"]];
        }
       
//        [[NSUserDefaults standardUserDefaults] setObject:_faceMap forKey:@"FaceMap"];
        _zhFaceMap = [[NSMutableDictionary alloc] init];
        for (NSString *enFace in _faceMap.allKeys) {
            [_zhFaceMap setObject:enFace forKey:_faceMap[enFace]];
        }

        //表情盘
        faceView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 190)];
        faceView.pagingEnabled = YES;
        faceView.contentSize = CGSizeMake((FACE_COUNT_ALL / facePageCount + 1) * screenWidth, 190);
        faceView.showsHorizontalScrollIndicator = NO;
        faceView.showsVerticalScrollIndicator = NO;
        faceView.delegate = self;
        
        for (int i = 1; i <= FACE_COUNT_ALL; i++) {

            FaceButton *faceButton = [FaceButton buttonWithType:UIButtonTypeCustom];
            faceButton.buttonIndex = i;
            
            [faceButton addTarget:self
                           action:@selector(faceButton:)
                 forControlEvents:UIControlEventTouchUpInside];
            
            //计算每一个表情按钮的坐标和在哪一屏
            CGFloat x = (((i - 1) % facePageCount) % faceRowCount) * FACE_ICON_SIZE + 6 + ((i - 1) / facePageCount * screenWidth);
            CGFloat y = (((i - 1) % facePageCount) / faceRowCount) * FACE_ICON_SIZE + 8;
            faceButton.frame = CGRectMake( x, y, FACE_ICON_SIZE, FACE_ICON_SIZE);
            
            [faceButton setImage:[UIImage imageNamed:[NSString stringWithFormat:@"em_%d", i]]
                        forState:UIControlStateNormal];

            [faceView addSubview:faceButton];
        }
        
        //添加PageControl
        facePageControl = [[GrayPageControl alloc]initWithFrame:CGRectMake((screenWidth - 100)/2, 190, 100, 20)];
        
        [facePageControl addTarget:self
                            action:@selector(pageChange:)
                  forControlEvents:UIControlEventValueChanged];
        
        facePageControl.numberOfPages = FACE_COUNT_ALL / facePageCount + 1;
        facePageControl.currentPage = 0;
        [self addSubview:facePageControl];
        
        //添加键盘View
        [self addSubview:faceView];
        
        //删除键
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
//        [back setTitle:@"删除" forState:UIControlStateNormal];
        [back setImage:[UIImage imageNamed:@"del_emoji_normal"] forState:UIControlStateNormal];
        [back setImage:[UIImage imageNamed:@"del_emoji_select"] forState:UIControlStateSelected];
        [back addTarget:self action:@selector(backFace) forControlEvents:UIControlEventTouchUpInside];
        back.frame = CGRectMake(screenWidth - 38 - 10, 182, 38, 28);
        [self addSubview:back];
    }

    return self;
}

//停止滚动的时候
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    [facePageControl setCurrentPage:faceView.contentOffset.x / screenWidth];
    [facePageControl updateCurrentPageDisplay];
}

- (void)pageChange:(id)sender {

    [faceView setContentOffset:CGPointMake(facePageControl.currentPage * screenWidth, 0) animated:YES];
    [facePageControl setCurrentPage:facePageControl.currentPage];
}

- (void)faceButton:(id)sender {

    NSInteger i = ((FaceButton*)sender).buttonIndex;
    if (self.inputTextField) {

        NSMutableString *faceString = [[NSMutableString alloc]initWithString:self.inputTextField.text];
        [faceString appendString:[_faceMap objectForKey:[NSString stringWithFormat:@"em_%ld", (long)i]]];
                self.inputTextField.text = faceString;
//        [faceString release];
    }

    if (self.inputTextView) {

        NSMutableString *faceString = [[NSMutableString alloc]initWithString:self.inputTextView.text];
        [faceString appendString:[_faceMap objectForKey:[NSString stringWithFormat:@"em_%ld", (long)i]]];
//        NSLog([_faceMap description]);
        self.inputTextView.text = faceString;
//        [faceString release];

        [delegate textViewDidChange:self.inputTextView];
    }
}

- (void)backFace{

    NSString *inputString;
    inputString = self.inputTextField.text;
    if ( self.inputTextView ) {

        inputString = self.inputTextView.text;
    }

    if ( inputString.length )
    {
        if (self.inputTextView.text.length <= 0)
            return;
        
        if (self.inputTextView.text.length >= FACE_NAME_LEN && [[self.inputTextView.text substringFromIndex:self.inputTextView.text.length - 1] isEqualToString:FACE_NAME_END])
        {
            BOOL isOverLen = NO;
            for (int i = FACE_NAME_LEN ; i > 2 ; i -- )
            {
                NSString *symbol = [self.inputTextView.text substringFromIndex:self.inputTextView.text.length - i];
                symbol = [symbol substringToIndex:1];
                if ([symbol isEqualToString:FACE_NAME_HEAD])
                {
                    self.inputTextView.text = [self.inputTextView.text substringToIndex:self.inputTextView.text.length - i];
                    isOverLen = YES;
                    break;
                }
            }
            if (!isOverLen)
            {
                self.inputTextView.text = [self.inputTextView.text substringToIndex:self.inputTextView.text.length - 1];
            }
        }
        else
        {
            self.inputTextView.text = [self.inputTextView.text substringToIndex:self.inputTextView.text.length - 1];
        }
        
        if ( self.inputTextView )
        {
            [delegate textViewDidChange:self.inputTextView];
        }
    }
}

/**
 * 解析输入的文本
 *
 * 根据文本信息分析出哪些是表情，哪些是文字
 */
- (void)getMessageRange:(NSString*)message :(NSMutableArray*)array
{
    if (message == nil)
    {
        return;
    }
    NSRange range = [message rangeOfString:FACE_NAME_HEAD];
    
    //判断当前字符串是否存在表情的转义字符串
    if ( range.length > 0 ) {
        
        if ( range.location > 0 ) {
            
            [array addObject:[message substringToIndex:range.location]];
            
            message = [message substringFromIndex:range.location];
            
            if ( message.length > FACE_NAME_LEN ) {
                NSRange Endrange = [message rangeOfString:FACE_NAME_END];
                [array addObject:[message substringToIndex:Endrange.location + 1]];
                
                message = [message substringFromIndex:Endrange.location + 1];
                [self getMessageRange:message :array];
            }
            else
                // 排除空字符串
                if ( message.length > 0 ) {
                    
                    [array addObject:message];
                }
        }
        else {
            
            if ( message.length > FACE_NAME_LEN ) {
                NSRange Endrange = [message rangeOfString:FACE_NAME_END];
                [array addObject:[message substringToIndex:Endrange.location + 1]];
                
                message = [message substringFromIndex:Endrange.location + 1];
                [self getMessageRange:message :array];
            }
            else
                // 排除空字符串
                if ( message.length > 0 ) {
                    
                    [array addObject:message];
                }
        }
    }
    else {
        
        [array addObject:message];
    }
}

/**
 *
 * 替换中文表情
 */
- (void)replaceZhFaceToEnFace:(NSMutableString*)message
{
    if (message == nil) {
        return;
    }
    NSLog(@"%@",message);

    NSString *tempStr = [NSString stringWithString:message];
    NSArray  *array   = nil;
    NSString *pattern = [NSString stringWithFormat:@"\\%@.*?\\%@", FACE_NAME_HEAD, FACE_NAME_END];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    if (regex != nil) {
        array = [regex matchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0, [tempStr length])];
    }
    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] init];
    for (NSTextCheckingResult *zhFaceResult in array) {
        NSRange resultRange = [zhFaceResult rangeAtIndex:0];
        NSString *zhFace = [tempStr substringWithRange:resultRange];
        if (!tempDic[zhFace]) {
            [tempDic setObject:@"" forKey:zhFace];
            NSString *enFaceStr = _zhFaceMap[zhFace];
            NSLog(@"%@",enFaceStr);
            if (enFaceStr != nil) {
                [message replaceOccurrencesOfString:zhFace withString:[NSString stringWithFormat:@"[%@]", enFaceStr] options:NSLiteralSearch range:NSMakeRange(0, [message length])];
            }
        }
    }
}

/**
 *
 * 替换英文表情
 */
- (void)replaceEnFaceToZhFace:(NSMutableString*)message
{
    if (message == nil)
    {
        return;
    }
    NSString *tempStr = [NSString stringWithString:message];
    NSArray *array = nil;
    NSString *pattern = [NSString stringWithFormat:@"\\%@.*?\\%@", FACE_NAME_HEAD, FACE_NAME_END];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    if (regex != nil) {
        array = [regex matchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0, [tempStr length])];
    }
    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] init];
    for (NSTextCheckingResult *enFaceResult in array) {
        NSRange resultRange = [enFaceResult rangeAtIndex:0];
        NSString *enFace = [tempStr substringWithRange:resultRange];
        if (!tempDic[enFace]) {
            [tempDic setObject:@"" forKey:enFace];
            NSString *noneEnFace = [enFace substringWithRange:NSMakeRange(1, enFace.length-2)];
            NSString *zhFaceStr = _faceMap[noneEnFace];
            if (zhFaceStr != nil) {
                [message replaceOccurrencesOfString:enFace withString:[NSString stringWithFormat:@"%@", zhFaceStr] options:NSLiteralSearch range:NSMakeRange(0, [message length])];
            }
        }
    }
}

/**
 *  获取文本尺寸
 */
- (NSValue *)getContentSize:(NSArray *)messageRange andwidth: (CGFloat) tablewidth andFontSize:(CGFloat)fontSize
{
    
    @synchronized ( self ) {
        
        
        CGFloat upX;
        
        CGFloat upY;
        
        CGFloat lastPlusSize;
        
        CGFloat viewWidth;
        
        CGFloat viewHeight;
        
        BOOL isLineReturn;
        
        UIFont *font = [UIFont systemFontOfSize:fontSize];
        
        isLineReturn = NO;
        
        upX = VIEW_LEFT;
        upY = VIEW_LINE_HEIGHT; //VIEW_TOP;
        
        for (int index = 0; index < [messageRange count]; index++) {
            
            NSString *str = [messageRange objectAtIndex:index];
            if ( [str hasPrefix:FACE_NAME_HEAD] ) {
                
                NSString *imageName = [str substringWithRange:NSMakeRange(1, str.length - 2)];
                
                NSString *imagePath = nil;
                
                    imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:@"png"];
                
                if ( imagePath ) {
                    
                    if ( upX > ( tablewidth - 20 ) ) {
                        
                        isLineReturn = YES;
                        
                        upX = VIEW_LEFT;
                        upY += (VIEW_LINE_HEIGHT - 5);
                    }
                    
                    upX += KFacialSizeWidth;
                    
                    lastPlusSize = KFacialSizeWidth;
                }
                else {
                    
                    for ( int index = 0; index < str.length; index++) {
                        
                        NSString *character = [str substringWithRange:NSMakeRange( index, 1 )];
                        
                        CGSize size = [character sizeWithFont:font
                                            constrainedToSize:CGSizeMake(tablewidth, VIEW_LINE_HEIGHT)];
                        
                        if ( upX > (tablewidth - 16)) {
                            
                            isLineReturn = YES;
                            
                            upX = VIEW_LEFT;
                            upY += (VIEW_LINE_HEIGHT - 5) ;
                        }
                        
                        upX += size.width;
                        lastPlusSize = size.width;
                    }
                }
            }
            else
            {
                for ( int index = 0; index < str.length; index++)
                {
                    
                    NSString *character = [str substringWithRange:NSMakeRange( index, 1 )];
                    CGSize size = [character sizeWithFont:font
                                        constrainedToSize:CGSizeMake(tablewidth, VIEW_LINE_HEIGHT)];
                    
                    if ( upX > (tablewidth - 16) )
                    {
                        isLineReturn = YES;
                        
                        upX = VIEW_LEFT;
                        upY += (VIEW_LINE_HEIGHT - 5);
                    }
                    
                    upX += size.width;
                    lastPlusSize = size.width;
                }
            }
        }
        
        if ( isLineReturn )
        {
            viewWidth = tablewidth;
        }
        else
        {
            
            viewWidth = tablewidth;
        }
        
        viewHeight = upY;
        
        NSValue *sizeValue = [NSValue valueWithCGSize:CGSizeMake( viewWidth, viewHeight )];
       
//        NSLog(@"%f", [sizeValue CGSizeValue].height);
        return sizeValue;
    }
}



@end
